import os, sys 
RootDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(RootDir)

from weiqi.dlgo.httpfrontend.server import get_web_app
from weiqi.dlgo.agent import DeepLearningAgent, RandmomAgent
from weiqi.dlgo.encoder import SevenPlaneEncoder
from weiqi.data.paraller_processor import GoDataProcessor
from weiqi.dlgo.networks.large import Layers
from weiqi.dlgo.agent import LoadPredictionAgent

import h5py
from keras.models import Sequential
from keras.layers import Dense

# 放在项目外
BotPath = os.path.join(os.path.dirname(RootDir), 'deep_bot.h5')

def save_h5file():
    rows, cols = 19,19
    nb_classes = rows*cols 
    encoder = SevenPlaneEncoder((rows,cols))
    processor = GoDataProcessor(encoder_name=encoder.name)
    x,y = processor.LoadData(num_samples=100)
    print('LoadData')
    input_shape = (encoder.num_planes, rows, cols)
    model = Sequential()
    layers = Layers(input_shape)
    for layer in layers:
        model.add(layer)
    model.add(Dense(nb_classes, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy'])
    model.fit(x,y, batch_size=128, epochs=20, verbose=1)

    bot = DeepLearningAgent(model, encoder)
    bot.Serialize(h5py.File(BotPath, 'w'))
    print('save success.')

def run_server():
    model_file = h5py.File(BotPath, 'r')
    agent = LoadPredictionAgent(model_file)
    web_app = get_web_app({'predict':agent})
    web_app.run()

def run():
    ''' 浏览器导航 127.0.0.1:5000/static/play_predict_19.html '''
    # save_h5file()
    run_server()

if __name__ == '__main__':
    run()